import urlcat from "urlcat";

/**
 * 基础请求函数
 * @param {string} url - API 请求路径（如 '/articles'）
 * @param {object} [options] - 请求配置项
 * @param {string} [options.method='GET'] - HTTP 方法
 * @param {object} [options.params] - URL 查询参数（如 { page: 1, limit: 10 }）
 * @param {object} [options.body] - 请求体数据
 * @returns {Promise<object>} 返回解析后的JSON数据
 *
 * @example
 * // 基础调用示例
 * request('/articles').then(data => console.log(data))
 *
 * @example
 * // 带查询参数的 GET 请求
 * request('/articles', {
 *   params: { page: 1, limit: 10 }
 * })
 *
 * @example
 * // POST 请求
 * // 提交表单数据
 * request('/auth/sign_in', {
 *   method: 'POST',
 *   body: { login: 'user', password: '123123' }
 * })
 */
export type Method = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
const request = async <D = Record<string, any>>(
  url: string,
  {
    method = "GET",
    params,
    body,
  }: {
    method?: Method;
    params?: any;
    body?: any;
  } = {}
): Promise<D> => {
  // 完整的接口地址
  const apiUrl = process.env.EXPO_PUBLIC_API_URL;
  const requestUrl = urlcat(apiUrl, url, params);

  // 请求头
  const headers = {
    Accept: "application/json",
    "Content-Type": "application/json",
    // 待完成：传递 token
  };

  const config = {
    method,
    headers,
    ...(body && { body: JSON.stringify(body) }),
  };

  const response = await fetch(requestUrl, config);

  if (!response.ok) {
    // 待完成：登录超时处理

    const { message, errors } = await response.json().catch(() => null);
    const error = new Error(message);
    error.status = response.status;
    error.errors = errors;
    throw error;
  }

  return await response.json();
};

export default request;
